using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class smartfishattack : MonoBehaviour
{
    // Start is called before the first frame update
    public float damage;
    public GameObject smartfish;
    public float starttime;
    public float continuetime;
    public float AttackTime;
    float AttackTimeKeeper;
    private Animator animator;
    private Collider2D collider2D;
    Transform transform;
    public int face = 1;
    float deltadistance;
    Transform player_transform;
    private smartfish Smartfish;
    public float StiffTime;
    public float RepelDistance;
    public int RepelTimes;
    public bool capture;
    public void Start()
    {
        animator = GetComponentInParent<Animator>();
        Smartfish = GetComponentInParent<smartfish>();
        collider2D = GetComponent<BoxCollider2D>();
        collider2D.enabled = false;
        transform = GetComponentInParent<Transform>();
        AttackTimeKeeper = AttackTime;
        deltadistance = GetComponentInParent<smartfish>().deltadistance;
        face = 1;
    }
    IEnumerator closecollider()
    {
        yield return new WaitForSeconds(continuetime);
        collider2D.enabled = false;
    }
    IEnumerator StartAttack()
    {
        yield return new WaitForSeconds(starttime);
        collider2D.enabled = true;
        StartCoroutine(closecollider());
    }
    void Attack()
    {
        if (player_transform.position.x + deltadistance >= transform.position.x && player_transform.position.x - deltadistance <= transform.position.x)
        {
            animator.SetTrigger("attack");
            StartCoroutine(StartAttack());
            AttackTimeKeeper = AttackTime;
        }
    }
    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.CompareTag("Enemy"))
        {
            if (capture&&other.GetComponent<EnemyBasic>().health < damage)
            {
                if (Random.Range(0f, 1f) < 0.05)
                {
                    Vector3 position = transform.position;
                    position.y += 1f;
                    position.x -= face * 1.5f;
                    Instantiate(smartfish, position, Quaternion.identity);
                }
            }
            other.GetComponent<EnemyBasic>().TakeDamage(damage, face, RepelTimes, RepelDistance, StiffTime);
        }
        if (other.gameObject.CompareTag("GrindingTower"))
        {

            other.GetComponent<Grinding>().TakeDamage(damage);
        }
    }
    private void getplayer()
    {
        player_transform = Smartfish.player_transform;
    }
    // Update is called once per frame
    public void Update()
    {
        getplayer();

        if (AttackTimeKeeper <= 0)
        {
            if (player_transform != null&&Smartfish.randrun==false)
            {
                Attack();
            }
            
        }
        else AttackTimeKeeper -= Time.deltaTime;
        //Debug.Log(enemyBasic.freeze);
    }
}
